import axios from 'axios'
import api from './api'
import qs from 'qs'
import root from './root'
// import store from '../src/store/store'
const request = axios.create({
  baseURL: root.httpUrl
})
request.defaults.timeout = 5000
function getToken () {
  return localStorage.getItem('token') || ''
}
// 请求拦截器
request.interceptors.request.use(
  response => {
    // 在请求发送之前做些什么
    let token, bearerToken
    token = getToken()
    bearerToken = `Bearer ${token}`
    response.headers.Authorization = bearerToken
    return response
  },
  error => {
    // 对请求错误做些什么
    return error
  }
)
// 响应拦截器
request.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    // let authHeader = response.headers.authorization
    // if (authHeader) {
    //   localStorage.setItem('token', authHeader)
    //   store.commit('user/saveToken', authHeader)
    // }
    return response
  },
  error => {
    // 对响应错误做点什么
    return error
  }
)
// export default request
export default {
  // post
  post (urlKey, params) {
    return request({
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'},
      method: 'post',
      url: api[urlKey],
      data: qs.stringify(params)
    })
  },
  // get
  get (urlKey, params) {
    return request({
      method: 'get',
      url: api[urlKey],
      params: params,
      headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}
    })
  },
  // form-data
  formDataPost (urlKey, params) {
    return request({
      method: 'post',
      url: api[urlKey],
      data: params,
      headers: {'Content-Type': 'multipart/form-data'}
    })
  }
}
